package com.example.aspect;

import com.example.annotation.AccessLevel;
import com.example.enums.AccessLevelEnum;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AccessControlAspect {

    @Before("@annotation(accessLevel)")
    public void checkAccessLevel(AccessLevel accessLevel) throws Exception {
        // 获取注解中的权限级别
        String requiredLevel = accessLevel.value();

        // 从 SecurityContext 获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new SecurityException("访问被拒绝：用户未认证");
        }

        // 获取用户角色
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String userRole = userDetails.getAuthorities().iterator().next().getAuthority();

        // 比较用户的权限级别和所需的权限级别
        if (!hasRequiredAccess(userRole, requiredLevel)) {
            throw new SecurityException("访问被拒绝：权限不足");
        }
    }

    private boolean hasRequiredAccess(String userRole, String requiredLevel) {
        // 获取用户的权限级别和所需的权限级别
        AccessLevelEnum userAccessLevel = AccessLevelEnum.fromRole(userRole);
        AccessLevelEnum requiredAccessLevel = AccessLevelEnum.fromRole(requiredLevel);

        // 只有当用户的权限级别大于等于所需的权限级别时，才允许访问
        return userAccessLevel.getLevel() >= requiredAccessLevel.getLevel();
    }
}
